package org.example.listener;


import com.microsoft.playwright.Page;
import io.qameta.allure.Attachment;
import org.testng.IHookCallBack;
import org.testng.IHookable;
import org.testng.ITestContext;
import org.testng.ITestResult;

public class TestResultListener implements IHookable {

    @Override
    public void run(IHookCallBack iHookCallBack, ITestResult iTestResult) {
        // 保证@Test注解标注的测试方法能够正常执行
        iHookCallBack.runTestMethod(iTestResult);

        // 获取 Playwright 的 Page 实例
        ITestContext context = iTestResult.getTestContext();
        Page page = (Page) context.getAttribute("page");

        // 判断用例是否失败
        if (iTestResult.getThrowable() != null && page != null) {
            // 如果测试失败，则截图
            saveScreenshotToAllure(takeScreenshotAsByte(page));
        }
    }

    @Attachment(value = "screenshot", type = "image/png")
    public byte[] saveScreenshotToAllure(byte[] data) {
        // 使用@Attachment注解来将截图作为附件添加到Allure报表中
        return data;
    }

    /**
     * 生成字节数组的截图数据
     * @param page
     * @return
     */
    public byte[] takeScreenshotAsByte(Page page) {
        return page.screenshot(new Page.ScreenshotOptions().setFullPage(true));
    }
}
